<template>
  <x-popup v-model="toggleStore.privacyModal.show" :radius="20" :height="420" title="隐私协议须知" type="center">
    <view class="content">
      <view class="tips">
        在使用本服务之前，请仔细阅读
        <text class="privacy-link" @click="handleReadPrivacy">
          {{ privacyContractName }}
        </text>
        。如果你同意{{ privacyContractName }}，请点击“同意”开始使用服务。
      </view>
      <view class="btns">
        <button class="btn x-btn x-btn-danger" @click="handleDisagreePrivacy">取消</button>
        <button
            :id="AGREE_ID"
            class="btn x-btn x-btn-primary"
            open-type="agreePrivacyAuthorization"
            @agreeprivacyauthorization="handleAgreePrivacy">
          同意
        </button>
      </view>
    </view>
  </x-popup>
</template>

<script setup>
import XPopup from '@/components/lib/popup.vue';
import privacyStore from "@/stores/framework/privacy";
import { ref } from 'vue';

// 同意按钮id
const AGREE_ID = 'agree-btn';
const toggleStore = privacyStore();
const privacyContractName = ref('隐私保护协议');

// 初始化隐私协议
initPrivacyInfo();

async function initPrivacyInfo() {
  const res = await getPrivacySetting();
  privacyContractName.value = res.privacyContractName;
}

/**
 * 检查api是否未实现，没实现返回true
 * @param {Object} api
 */
function isApiNotImplemented (api) {
  return uni[api] === undefined || [api] && uni[api].toString().indexOf("is not yet implemented") > -1
}

function getPrivacySetting() {
  return new Promise((resolve) => {
    if(uni['getPrivacySetting']) {
      uni.getPrivacySetting({
        success:(res) => {
          resolve(res);
        }
      })
    }
  })
}

/**
 * 阅读隐私协议
 */
function handleReadPrivacy() {
  uni.openPrivacyContract();
}

/**
 * 关闭弹窗
 */
function closeModal() {
  toggleStore.togglePrivacyModal(false);
}

/**
 * 拒绝隐私协议
 */
function handleDisagreePrivacy() {
  closeModal();
  toggleStore.privacyModal.resolvePrivacyAuthorization({
    event: 'disagree',
  });
}

/**
 * 同意隐私协议
 */
function handleAgreePrivacy() {
  closeModal();
  toggleStore.privacyModal.resolvePrivacyAuthorization({
    buttonId: AGREE_ID,
    event: 'agree',
  });
}
</script>

<style lang="less" scoped>
.content {
  width: 580rpx;
  padding: 0 40rpx;
  border-radius: 20rpx;
  box-sizing: border-box;
  font-size: 30rpx;
  height: 100%;
}

.tips {
  padding-top: 32rpx;
  box-sizing: border-box;
  font-size: 32rpx;
  text-align: justify;

  .privacy-link {
    color: #34a5fc;
  }
}

.btns {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 60rpx;

  .btn {
    width: 200rpx;
    height: 72rpx;
  }
}
</style>
